﻿namespace NuGetCop.MSBuild.Tasks.Configuration.Readers
{
    using System;
    using System.Diagnostics.Contracts;
    using System.IO;
    using System.Net;

    internal sealed class NuGetCopSettingsWebReader : INuGetCopSettingsReader<Uri>
    {
        private readonly INuGetCopSettingsReader<Stream> streamSettingsReader;

        public NuGetCopSettingsWebReader(
            INuGetCopSettingsReader<Stream> streamSettingsReader)
        {
            Contract.Requires(streamSettingsReader != null);

            this.streamSettingsReader = streamSettingsReader;
        }

        public NuGetCopSettings ReadSettings(Uri sourceUri)
        {
            var getSettingRequest = WebRequest.Create(sourceUri);
            var getSettingsResponse = getSettingRequest.GetResponse();

            NuGetCopSettings resultSettings;

            using (var stream = getSettingsResponse.GetResponseStream())
            {
                resultSettings = streamSettingsReader.ReadSettings(stream);                
            }

            return resultSettings;
        }
    }
}
